package com.hxy.apartment.controller;

import com.hxy.apartment.entities.Resident;
import com.hxy.apartment.entities.Result;
import com.hxy.apartment.entities.Sign;
import com.hxy.apartment.entities.User;
import com.hxy.apartment.service.FaceService;
import com.hxy.apartment.utils.Util;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Objects;

@RestController
@CrossOrigin
public class IndexController {

    @Resource
    private FaceService faceService;

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        return faceService.login(user);
    }

    @PostMapping("/register")
    public Result register(@RequestParam("file") MultipartFile file, @Valid Resident resident, BindingResult result) throws IOException {
        if (result.hasErrors()) {
            return Result.error(Objects.requireNonNull(result.getFieldError()).getDefaultMessage());
        }
        BASE64Encoder encoder = new BASE64Encoder();
        String image = encoder.encode(file.getBytes());
        int res = faceService.register(image, resident);
        if (res == 1) {
            return Result.success(resident.getName() + "用户的信息录入成功");
        }
        return Result.error("信息录入失败");
    }

    @PostMapping("/sign")
    public Result sign(@RequestParam("file") MultipartFile file) throws IOException {
        BASE64Encoder encoder = new BASE64Encoder();
        String image = encoder.encode(file.getBytes());
        return faceService.check(image);
    }

    @GetMapping("/get")
    public Result get0() {
        return faceService.get(Util.getDate());
    }

    @GetMapping("/get/{time}")
    public Result get(@PathVariable String time) {
        return faceService.get(time);
    }

    @PostMapping("/vacation")
    public Result vacation(@RequestBody Sign sign) {
        return faceService.vacation(sign);
    }

}
